/**
 * 
 */
package com.mvc.controller.healthmanager;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.huangqj.consant.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.mvc.model.base.Json;
import com.mvc.model.healthmanager.archive.Teeth;
import com.mvc.service.healthmanager.TeethServiceI;

/**
 * @author qingjie
 *
 */
@RequestMapping("/teeth")
@Controller
public class TeethController {

	@Autowired
	private TeethServiceI tsi;
	
	@RequestMapping("/saveTeeth")
	@ResponseBody
	public Json saveTeeth(HttpServletRequest request,Teeth teeth) throws Exception{
		String json = request.getParameter("json");
		System.out.println("未转化数据：" + json);
//		json = URLDecoder.decode(json, "utf-8");
		String[] s = json.split("=");
		if (s.length > 1) {
			json = s[1];
		}
		Teeth t = new Teeth();
		if (!json.isEmpty()) {
			t = JSON.parseObject(json, Teeth.class);
			t.setId(null);
		}
		teeth = tsi.saveOrUpdate(t);
		Json j = new Json();
		if(teeth!=null&&!json.isEmpty()){
			j.setMsg("保存成功");
			j.setSuccess(true);
			j.setObj(teeth);
		}else{
			j.setMsg("保存失败");
			j.setSuccess(false);
		}
		return j;
	}
	
	@RequestMapping(value="/saveTeeth", method=RequestMethod.POST,consumes = "application/json")
	@ResponseBody
	public Json saveTeeth(@RequestBody List<Teeth> ts,HttpServletRequest request) throws Exception{
		System.out.println("未转化的数据："+JSON.toJSONString(ts));
		Json j = new Json();
		List<Teeth> list = new ArrayList<Teeth>();
		if(ts.size()>0){
			for(Teeth t : ts){
				Long appLocalId = ValidatorUtil.isNullOnLong(t.getId())?null:t.getId();
				t.setId(null);
				Teeth teeth = new Teeth();
				teeth = tsi.saveOrUpdate(t);
				if(teeth!=null&&!ValidatorUtil.isNullOnLong(teeth.getId())){
					teeth.setRespCode(0);
				}else{
					teeth.setRespCode(-1);
				}
				teeth.setAppLocalId(appLocalId);
				list.add(teeth);
			}
			j.setMsg("数据已经处理！");
			j.setSuccess(true);
			j.setObj(list);
		}else{
			j.setMsg("数据为空");
			j.setSuccess(false);
		}
		return j;
	}
}
